package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func main() {
	r := gin.Default()
	r.Use(runTime(), Hook404(), nextTest()) //第一种方式全局使用
	group := r.Group("demo")
	group.Use(runTime()).POST("/test1", func(c *gin.Context) {}) //第二种方式,分组使用
	group.GET("/test2", runTime(), func(c *gin.Context) {})      //第三种,单个请求使用
	group.GET("/test", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "this is test",
		})
	})
	r.GET("/hook", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": "this is msg",
		})
	})
	r.Run(":8888")
}

func runTime() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		time.Sleep(time.Second * 2)
		//c.Next()
		since := time.Since(start)
		fmt.Println("运行时间", since)
	}
}

func nextTest() gin.HandlerFunc {
	return func(context *gin.Context) {
		fmt.Println("next auto")
	}
}

func Hook404() gin.HandlerFunc {
	return func(c *gin.Context) {
		log.Println("hook 404")
		c.Next()
		status := c.Writer.Status()
		if status == 404 {
			c.JSON(http.StatusOK, gin.H{
				"msg": "页面找不到",
			})
			c.Abort()
		}
	}
}
